package com.wuage.interfaces.file;

import com.wuage.infrastructure.exception.BizException;
import com.wuage.infrastructure.status.BizResultCode;
import com.wuage.infrastructure.utils.OssUtil;
import com.wuage.infrastructure.utils.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @author Shynin
 * @version 1.0
 * @date 2020-09-09 10:41
 */
@Slf4j
@Controller
@Api(tags = "{文件}-相关接口")
@RequestMapping("/file")
public class FileController {

    @Resource
    private OssUtil ossUtil;

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation("上传文件")
    public Response<String> upload(@RequestParam("files") MultipartFile files) {
        String result = null;
        try {
            result = ossUtil.uploadFile(files.getBytes(), files.getOriginalFilename());
        } catch (IOException e) {
            throw new BizException(BizResultCode.FILE_UPLOAD_ERROR);
        }
        return new Response<>(result);
    }

    @ApiOperation("下载文件")
    @GetMapping("/download")
    public void download(@ApiParam("日期") @RequestParam("url") String url
            , HttpServletResponse response) throws Exception {
        String filename = url.substring(url.lastIndexOf("/") + 1);

        URL urlDown = new URL(url);

        URLConnection uc = urlDown.openConnection();
        InputStream inputStream = uc.getInputStream();
        response.reset();
        // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
        response.addHeader("Content-Disposition",
                "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes(StandardCharsets.UTF_8),
                        "iso8859-1"));
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        byte[] b = new byte[1024];
        int len = 0;
        while((len = inputStream.read(b)) != -1) {
            os.write(b,0,len);
        }
        os.flush();
        os.close();
    }

}
